#include "LicenseCheck.h"

#if defined(SG_LICENSE_CHECK)

#include <filesystem>
#include <iostream>
#include <string>
#include <unordered_map>

#include <boost/dll/runtime_symbol_info.hpp>

#include "licensecc/licensecc.h"

namespace fs = std::filesystem;

bool SG::Utility::SGCheckLicense (bool isAsk)
{
    const std::unordered_map<LCC_EVENT_TYPE, std::string> stringByEventType = {
        { LICENSE_OK, "OK " },
        { LICENSE_FILE_NOT_FOUND, "license file not found ." },
        { LICENSE_SERVER_NOT_FOUND, "license server can't be contacted ." },
        { ENVIRONMENT_VARIABLE_NOT_DEFINED, "environment variable not defined ." },
        { FILE_FORMAT_NOT_RECOGNIZED, "license file has invalid format (not .ini file) ." },
        { LICENSE_MALFORMED, "some mandatory field are missing, or data can't be fully read. " },
        { PRODUCT_NOT_LICENSED, "this product was not licensed ." },
        { PRODUCT_EXPIRED, "your license expired ." },
        { LICENSE_CORRUPTED, "license signature didn't match with current license ." },
        { IDENTIFIERS_MISMATCH, "Calculated identifier and the one provided in license didn't match ." }
    };
    //
    // std::string     licensePath = "./license.dat";
    std::string licensePath = boost::dll::program_location ().parent_path ().string () + "/license.dat";
    // std::cout << "license path: " << licensePath << '\n';
    LicenseLocation location = { LICENSE_PATH };
    std::copy (licensePath.begin (), licensePath.end (), location.licenseData);

    LicenseInfo          licenseInfo;
    const LCC_EVENT_TYPE result = acquire_license (nullptr, &location, &licenseInfo);

    if (result != LICENSE_OK)
    {
        std::cout << "**************************************************\n            ";
        std::cout << stringByEventType.at (result) << "\n";
        std::cout << "**************************************************\n";
        if (isAsk)
        {
            size_t pc_id_sz = LCC_API_PC_IDENTIFIER_SIZE + 1;
            char   pc_identifier[LCC_API_PC_IDENTIFIER_SIZE + 2];
            // 使用stdin 询问用户是否需要生成一个新的license
            std::cout << "do you want to generate a new license? (y/n): ";
            char x = 'y';
            std::cin >> x;
            if (x == 'y')
            {
                if (identify_pc (STRATEGY_DEFAULT, pc_identifier, &pc_id_sz, nullptr))
                {
                    std::cout << "\r\nplease send this signature to support personnel. \r\nsignature: " << std::string (pc_identifier)
                              << '\n';
                }
                else
                {
                    std::cout << "Failed to identify your PC!";
                }
            }
        }
#ifdef _WIN32
        system ("pause");
#endif
        exit (-1);
    }
    return true;
}
#else

bool SG::Utility::SGCheckLicense (bool isAsk)
{
    return false;
}
#endif
